package com.springdata.jpa.dao;

import com.springdata.jpa.pojo.Student;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * @ClassName StudentRepository
 * @Desc student dao 层
 * @Author xiaoding
 * @Date 2022-11-05 22:40
 * @Version 1.0
 */
public interface StudentRepository extends JpaRepository<Student,Integer>, JpaSpecificationExecutor<Student> {
    // 使用 ? 作为占位，序号从1开始
    //使用增删改JPQL，需要在接口方法上加@Modifying
    //测试的方法需要加上@Transactional,关闭自动回滚@Rollback(false)
    @Query("FROM Student WHERE name like ?1")
    List<Student> findStudentByName(String name);

    @Query("UPDATE Student SET name = :name WHERE id = :id")
    @Modifying
    void updateById(@Param("name") String name, @Param("id") Integer id);

    //使用原生SQL
    @Query(value = "UPDATE t_student SET name = ?1 WHERE id = ?2",nativeQuery = true)
    @Modifying
    void updateById02(String name,Integer id);

    // 基于命名规则定义方法,只能用于查询
    List<Student> findByNameAndId(String name,Integer Id);

    //命名规则查询配合分页使用
    Page<Student> findStudentsByNameLike(String name, Pageable pageable);

    //命名规则查询配合排序使用
    List<Student> findStudentsByNameLike(String name, Sort sort);
}
